#!/bin/bash

pid=""
port=""

getPid() {
  if [ -n "$port" ]; then
    echo "获取指定端口（$port）的进程"
    pid=$(netstat -tunlp | grep "$port" | awk '{print $7}' | awk -F'/' '{print $1}')
  else
    echo "获取默认端口（8080）的进程"
    pid=$(netstat -tunlp | grep 8080 | awk '{print $7}' | awk -F'/' '{print $1}')
  fi
}

while getopts ":p:" opt; do
  case $opt in
  p)
    port=$OPTARG
    ;;
  ?)
    echo "未知参数"
    exit 1
    ;;
  esac
done

getPid
if [ -n "$pid" ]; then
  echo "正在杀死指定进程 $pid"
  kill -9 $pid
else
  echo "该端口未被占用"
fi

echo "启动进程"
nohup java -jar /root/springboot-01-helloworld-0.0.1-SNAPSHOT.jar >nohup.log 2>&1 &

echo "正在运行的进程pid为 $!"
